import {Component, ElementRef, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {HttpProvider} from "@providers/http";
import {DialogProvider} from "@providers/dialog";
import {StorageProvider} from "@providers/storage";
import {pinyin} from "@common/pinyin";

/**
 * Generated class for the MContactsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-manager-contacts',
  templateUrl: 'manager-contacts.html',
})
export class ManagerContactsPage {
  @ViewChild(Content) content: Content;
  userInfo: any;
  aletters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  formatContacts: any[] = [];//格式化之后的联系人数据
  searchContacts: any[] = [];//搜索之后的联系人数据
  contactsNum: number = 0;//格式化之后的联系人数量
  isSearching: boolean = false;//控制搜索框的显示和隐藏

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private toastCtrl: ToastController,
              private http: HttpProvider,
              private dialog: DialogProvider,
              private storageService: StorageProvider,
              private elementRef: ElementRef) {
    this.userInfo = this.storageService.read('userInfo');
  }

  ionViewWillEnter() {
    this.getRY();
  }

  push(page: string, data?: any) {
    this.navCtrl.push(page, data);
  }

  //搜索事件
  search(searchText: any) {
    if (searchText == undefined) {
      searchText = '';
    } else {
      searchText = searchText.trim();
    }
    this.searchContacts = [];
    if (searchText) {
      this.formatContacts.forEach(value => {
        let search = value.value.filter(val => {
          return (val.VALUE.indexOf(searchText) > -1 || val.LXDH.indexOf(searchText) > -1);
        });
        if (search.length > 0) {
          this.searchContacts.push({
            'key': value.key,
            'value': search
          })
        }
      })
    }

  }

  //获取人员
  getRY() {
    this.http.post("/Inbound/invoke.do", {
      interfaceId: "csm.css.jcdy.qcfwquery.fwry",
      data: JSON.stringify({'RYXX01': this.userInfo.RYXX01})
    }).subscribe(message => {
      this.formatContacts = [];
      this.formattdContacts(message.data);
    }, error => {
      this.dialog.showAlert('请检查网络！' + error);
      this.dialog.hideLoading();
    });
  }

  //格式化查到的联系人
  formattdContacts(contacts: any[]) {
    this.contactsNum = contacts.length;
    contacts.forEach((value, index) => {
      value.pinyinName = pinyin.getFullChars(value.VALUE);
      let camelChar = pinyin.getCamelChars(value.VALUE).substring(0, 1).toLocaleUpperCase();
      let temp = this.formatContacts.filter(value => {
        return value.key == camelChar;
      });
      if (temp.length == 0) {
        let arr = new Array();
        arr.push(value);
        this.formatContacts.push({
          key: camelChar,
          value: arr
        });
      } else {
        temp[0].value.push(value)
      }
    });
    this.formatContacts = this.sortContacts(this.formatContacts);
  }

  //对格式化之后的联系人进行排序
  sortContacts(formatContacts) {
    //首字母排序
    formatContacts.sort(function (a, b) {
      if (a.key < b.key) {
        return -1;
      } else if (a.key > b.key) {
        return 1;
      } else {
        return 0;
      }
    });

    //每组内部排序
    formatContacts.forEach(value => {
      value.value.sort(function (a, b) {
        if (a.pinyinName < b.pinyinName) {
          return -1;
        } else if (a.key > b.key) {
          return 1;
        } else {
          return 0;
        }
      });
    });

    return formatContacts;

  }

  /**
   *定位查找首字母对应的通讯录
   */
  scrollToTop(letter) {
    this.show(letter, 1000);
    if (this.elementRef.nativeElement.querySelector("ion-item-divider#" + letter)) {
      let scrollTop = this.elementRef.nativeElement.querySelector("ion-item-divider#" + letter).offsetTop;
      this.content.scrollTo(0, scrollTop, 300);
    }
  }

  show(message: string = '操作完成', duration: number = 2500) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: duration,
      position: 'middle',
      cssClass: 'hj-toast'
    });
    toast.present();
  };
}
